/**
 * 详情对话框
 */
var HxOrderPutDetailedInfoDlg = {
    data: {
        orderPutId: "",
        goodsName: "",
        goodsNumber: "",
        goodsPcode69: "",
        goodsSpecs: "",
        psUnit: "",
        psRate: "",
        psNum: "",
        zpUnit: "",
        zpRate: "",
        zpNum: "",
        sumNum: "",
        goodsWeight: "",
        putWeight: "",
        goodsVolume: "",
        putVolume: "",
        goodsPrice: "",
        putMoney: "",
        batch: "",
        detailedDate: "",
        notes: "",
        v1: "",
        v2: "",
        v3: "",
        v4: "",
        v5: "",
        v6: ""
    }
};

var HxBasicGoodsInfoDlg = {
    data: {
		id:"",
        goodsCustomerId: "",
        goodsCustomerName: "",
        goodsName: "",
        goodsNumber: "",
        goodsPcode69: "",
        goodsXcode69: "",
        goodsHelpcode: "",
        goodsSpecs: "",
        goodsBigtype: "",
        goodsBrand: "",

        jibenUnit: "",
        kcUnit: "",
        kcRate: "",
        cgUnit: "",
        cgRate: "",
        pfUnit: "",
        pfRate: "",
        psUnit: "",
        psRate: "",

        anquanNum: "",
        goodsBottom: "",
        goodsLamination: "",
        goodsTraylayer: "",
        goodsSupportvolume: "",
        length: "",
        height: "",
        width: "",
        goodsWeight: "",
        goodsVolume: "",
        goodsChargingCg: "",
        goodsChargingPs: "",
        goodsChargingPf: "",
        goodsWarranty: ""
    }
};
layui.use(['form', 'admin', 'ax','laydate'], function () {
    var $ = layui.jquery;
    var $ax = layui.ax;
    var form = layui.form;
    var admin = layui.admin;
    var laydate = layui.laydate;

    //让当前iframe弹层高度适应
    admin.iframeAuto();

    //选择生产日期后，填入批次 
    laydate.render({
    	elem:'#detailedDate'
    })

    //获取详情信息，填充表单
    var ajax = new $ax(Feng.ctxPath + "/hxOrderPutDetailed/detail?id=" + Feng.getUrlParam("id"));
    var result = ajax.start();
    form.val('hxOrderPutDetailedForm', result.data);
    //获取详情信息，填充表单
    var ajax2 = new $ax(Feng.ctxPath + "/hxBasicGoods/detail?id=" + Feng.getUrlParam("goodsId"));
    var result2 = ajax2.start();
	HxBasicGoodsInfoDlg.data.id = result2.data.id;
	HxBasicGoodsInfoDlg.data.goodsName = result2.data.goodsName;//商品名称
	HxBasicGoodsInfoDlg.data.goodsNumber = result2.data.goodsNumber;
	HxBasicGoodsInfoDlg.data.goodsPcode69 = result2.data.goodsPcode69;
	HxBasicGoodsInfoDlg.data.goodsSpecs = result2.data.goodsSpecs;

	HxBasicGoodsInfoDlg.data.jibenUnit = result2.data.jibenUnit;
	HxBasicGoodsInfoDlg.data.kcUnit = result2.data.kcUnit;
	HxBasicGoodsInfoDlg.data.kcRate = result2.data.kcRate;
	HxBasicGoodsInfoDlg.data.cgUnit = result2.data.cgUnit;
	HxBasicGoodsInfoDlg.data.cgRate = result2.data.cgRate;
	HxBasicGoodsInfoDlg.data.pfUnit = result2.data.pfUnit;
	HxBasicGoodsInfoDlg.data.pfRate = result2.data.pfRate;
	HxBasicGoodsInfoDlg.data.psUnit = result2.data.psUnit;
	HxBasicGoodsInfoDlg.data.psRate = result2.data.psRate;

	HxBasicGoodsInfoDlg.data.goodsSupportvolume = result2.data.goodsSupportvolume;
	HxBasicGoodsInfoDlg.data.goodsVolume = result2.data.goodsVolume;
	HxBasicGoodsInfoDlg.data.goodsWeight = result2.data.goodsWeight;
	HxBasicGoodsInfoDlg.data.goodsChargingCg = result2.data.goodsChargingCg;
	HxBasicGoodsInfoDlg.data.goodsChargingPs = result2.data.goodsChargingPs;
	HxBasicGoodsInfoDlg.data.goodsChargingPf = result2.data.goodsChargingPf;
	let uniqueOptions = [];
	let existingOptions = [];

	$("#unit").empty();

// 先将所有要添加的选项值存储到一个数组中
	let allOptions = [
		{ value: HxBasicGoodsInfoDlg.data.jibenUnit, text: HxBasicGoodsInfoDlg.data.jibenUnit },
		{ value: HxBasicGoodsInfoDlg.data.kcUnit, text: HxBasicGoodsInfoDlg.data.kcUnit },
		{ value: HxBasicGoodsInfoDlg.data.cgUnit, text: HxBasicGoodsInfoDlg.data.cgUnit },
		{ value: HxBasicGoodsInfoDlg.data.pfUnit, text: HxBasicGoodsInfoDlg.data.pfUnit },
		{ value: HxBasicGoodsInfoDlg.data.psUnit, text: HxBasicGoodsInfoDlg.data.psUnit }
	];

// 对数组进行去重
	allOptions.forEach(option => {
		if (!existingOptions.includes(option.value)) {
			uniqueOptions.push(option);
			existingOptions.push(option.value);
		}
	});

// 添加去重后的选项
	uniqueOptions.forEach(option => {
		$("#unit").append(new Option(option.value, option.text));
	});
	form.render("select");
    //表单提交事件
    form.on('submit(btnSubmit)', function (data) {
        var ajax = new $ax(Feng.ctxPath + "/hxOrderPutDetailed/editItem", function (data) {
        	if (data.success) {
	            Feng.success("更新成功！");
	        	var Index = parent.layer.getFrameIndex(window.name);
	            parent.layer.close(Index);
			} else {
                Feng.error("更新失败！"+data.message);
			}
        }, function (data) {
            Feng.error("更新失败！" + data.responseJSON.message)
        });
		data.field.unitType = unitType;
        ajax.set(data.field);
        ajax.start();

        return false;
    });

    //点击选择商品名称
    $('#choiceGoods').click(function () {
        layer.open({
            type: 2,
            title: '选择商品',
            area: ['1000px', '450px'],
            content: Feng.ctxPath + '/hxBasicGoods/toChoiceGoods_od',
            end: function () {
                $("#goodsId").val(HxBasicGoodsInfoDlg.data.id);
                $("#goodsName").val(HxBasicGoodsInfoDlg.data.goodsName);//商品名称
                $("#goodsNumber").val(HxBasicGoodsInfoDlg.data.goodsNumber);
                $("#goodsPcode69").val(HxBasicGoodsInfoDlg.data.goodsPcode69);
                $("#goodsSpecs").val(HxBasicGoodsInfoDlg.data.goodsSpecs);

                var goodsVolume = HxBasicGoodsInfoDlg.data.goodsVolume
                var goodsWeight = HxBasicGoodsInfoDlg.data.goodsWeight
                var goodsSupportvolume = HxBasicGoodsInfoDlg.data.goodsSupportvolume



				$("#unit").empty();
				goodsInfo = {};
				//配送单位
				let obj = {};
				obj['unit'] = HxBasicGoodsInfoDlg.data.psUnit;
				obj['rate'] = HxBasicGoodsInfoDlg.data.psRate;
				goodsInfo['psUnit']=obj;
				//基本单位
				obj = {};
				obj['unit'] = HxBasicGoodsInfoDlg.data.jibenUnit;
				obj['rate'] = 1;
				goodsInfo['jibenUnit']=obj;
				//库存单位
				obj = {};
				obj['unit'] = HxBasicGoodsInfoDlg.data.kcUnit;
				obj['rate'] = HxBasicGoodsInfoDlg.data.kcRate;
				goodsInfo['kcUnit']=obj;
				//采购单位
				obj = {};
				obj['unit'] = HxBasicGoodsInfoDlg.data.cgUnit;
				obj['rate'] = HxBasicGoodsInfoDlg.data.cgRate;
				goodsInfo['cgUnit']=obj;
				//批发单位
				obj = {};
				obj['unit'] = HxBasicGoodsInfoDlg.data.pfUnit;
				obj['rate'] = HxBasicGoodsInfoDlg.data.pfRate;
				goodsInfo['pfUnit']=obj;
				//商品其他信息
				obj = {};
				obj['goodsChargingPs'] = HxBasicGoodsInfoDlg.data.goodsChargingPs;
				obj['goodsVolume'] = goodsVolume;
				obj['goodsWeight'] = goodsWeight;
				goodsInfo['goods']=obj;

				unitInfo = {};
				//配送单位
				unitInfo[HxBasicGoodsInfoDlg.data.psUnit]=HxBasicGoodsInfoDlg.data.psRate;
				$("#unit").append(new Option( HxBasicGoodsInfoDlg.data.psUnit, HxBasicGoodsInfoDlg.data.psUnit));// 下拉菜单里添加元素
				//基本单位
				if(!unitInfo[HxBasicGoodsInfoDlg.data.jibenUnit]){
					unitInfo[HxBasicGoodsInfoDlg.data.jibenUnit]=1;
					$("#unit").append(new Option( HxBasicGoodsInfoDlg.data.jibenUnit, HxBasicGoodsInfoDlg.data.jibenUnit));// 下拉菜单里添加元素
				}
				//库存单位
				if(!unitInfo[HxBasicGoodsInfoDlg.data.kcUnit]){
					unitInfo[HxBasicGoodsInfoDlg.data.kcUnit]=HxBasicGoodsInfoDlg.data.kcRate;
					$("#unit").append(new Option( HxBasicGoodsInfoDlg.data.kcUnit, HxBasicGoodsInfoDlg.data.kcUnit));// 下拉菜单里添加元素
				}
				//采购单位
				if(!unitInfo[HxBasicGoodsInfoDlg.data.cgUnit]){
					unitInfo[HxBasicGoodsInfoDlg.data.cgUnit]=HxBasicGoodsInfoDlg.data.cgRate;
					$("#unit").append(new Option( HxBasicGoodsInfoDlg.data.cgUnit, HxBasicGoodsInfoDlg.data.cgUnit));// 下拉菜单里添加元素
				}
				//批发单位
				if(!unitInfo[HxBasicGoodsInfoDlg.data.pfUnit]){
					unitInfo[HxBasicGoodsInfoDlg.data.pfUnit]=HxBasicGoodsInfoDlg.data.pfRate;
					$("#unit").append(new Option( HxBasicGoodsInfoDlg.data.pfUnit, HxBasicGoodsInfoDlg.data.pfUnit));// 下拉菜单里添加元素
				}
				//配送单位
				if(!unitInfo[HxBasicGoodsInfoDlg.data.psUnit]){
					unitInfo[HxBasicGoodsInfoDlg.data.psUnit]=HxBasicGoodsInfoDlg.data.psRate;
					$("#unit").append(new Option( HxBasicGoodsInfoDlg.data.psUnit, HxBasicGoodsInfoDlg.data.psUnit));// 下拉菜单里添加元素
				}

				form.render("select");
				unitType = "配送单位";
				$("#unit").val(HxBasicGoodsInfoDlg.data.psUnit);
				$("#rate").val(HxBasicGoodsInfoDlg.data.psRate);

				if(parseFloat(HxBasicGoodsInfoDlg.data.psRate) == parseFloat(HxBasicGoodsInfoDlg.data.cgRate)){
					$("#goodsVolume").val(goodsVolume);
					$("#goodsWeight").val(goodsWeight);
					$("#goodsSupportvolume").val(goodsSupportvolume);
				}
				if(parseFloat(HxBasicGoodsInfoDlg.data.psRate) < parseFloat(HxBasicGoodsInfoDlg.data.cgRate)){
					//如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
					var div = accDiv(HxBasicGoodsInfoDlg.data.cgRate,HxBasicGoodsInfoDlg.data.psRate)
					var divv_v = accDiv(goodsVolume,div).toFixed(4)
					$("#goodsVolume").val(divv_v);
					var divv_w = accDiv(goodsWeight,div).toFixed(3)
					$("#goodsWeight").val(divv_w);
					var divv_s = accMul(goodsSupportvolume,div)
					$("#goodsSupportvolume").val(divv_s);
				}
				if(parseFloat(HxBasicGoodsInfoDlg.data.psRate) > parseFloat(HxBasicGoodsInfoDlg.data.cgRate)){
					//如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
					var div = accDiv(HxBasicGoodsInfoDlg.data.psRate,HxBasicGoodsInfoDlg.data.cgRate)
					var divm_v = accMul(goodsVolume,div).toFixed(4)
					$("#goodsVolume").val(divm_v);
					var divm_w = accMul(goodsWeight,div).toFixed(3)
					$("#goodsWeight").val(divm_w);
					$("#goodsSupportvolume").val(accDiv(goodsSupportvolume,div).toFixed(4));

				}
				$("#goodsPrice").val(accMul(HxBasicGoodsInfoDlg.data.cgRate,HxBasicGoodsInfoDlg.data.goodsChargingCg).toFixed(3));


            }
        });
    });
	function gx(){
		$("#num").val("");
		$("#zpNum").val("0");
		$("#sumNum").val("");
		$("#putVolume").val("");
		$("#putWeight").val("");
		$("#putMoney").val("");
	}
	form.on('select(unit)', function(){
		var goodsName = $("#goodsName").val();
		let unitVal = $("#unit").val();

		if (unitVal==HxBasicGoodsInfoDlg.data.psUnit){
			unitType = "配送单位";
			$("#rate").val(HxBasicGoodsInfoDlg.data.psRate);

		} else if (unitVal==HxBasicGoodsInfoDlg.data.jibenUnit){
			unitType = "基本单位";
			$("#rate").val(1);
		} else if (unitVal==HxBasicGoodsInfoDlg.data.kcUnit){
			unitType = "库存单位";
			$("#rate").val(HxBasicGoodsInfoDlg.data.kcRate);
		} else if (unitVal==HxBasicGoodsInfoDlg.data.cgUnit){
			unitType = "采购单位";
			$("#rate").val(HxBasicGoodsInfoDlg.data.cgRate);

		} else if (unitVal==HxBasicGoodsInfoDlg.data.pfUnit){
			unitType = "批发单位";
			$("#rate").val(HxBasicGoodsInfoDlg.data.pfRate);
		}
		var unitRate = $("#rate").val();
		//根据单位名称获取对应的换算率
		// let unitRate = unitInfo[unitVal];
		// console.log(unitInfo)
		// $("#rate").val(unitRate);
		if (goodsName == null || goodsName == '') {

		} else {
			var goodsVolume = HxBasicGoodsInfoDlg.data.goodsVolume
			var goodsWeight = HxBasicGoodsInfoDlg.data.goodsWeight
			var goodsSupportvolume = HxBasicGoodsInfoDlg.data.goodsSupportvolume
			if(parseFloat(unitRate) == parseFloat(goodsInfo['cgUnit'].rate)){
				$("#goodsVolume").val(goodsVolume);
				$("#goodsWeight").val(goodsWeight);
			}
			if(parseFloat(unitRate) < parseFloat(goodsInfo['cgUnit'].rate)){
				//如果配送换算率 小于 采购换算率：  配送体积  =  采购体积/（采购换算率/配送换算率）
				var div = accDiv(goodsInfo['cgUnit'].rate,unitRate)
				var divv_v = accDiv(goodsVolume,div).toFixed(4)
				$("#goodsVolume").val(divv_v);
				var divv_w = accDiv(goodsWeight,div).toFixed(3)
				$("#goodsWeight").val(divv_w);
			}
			if(parseFloat(unitRate) > parseFloat(goodsInfo['cgUnit'].rate)){
				//如果配送换算率 大于 采购换算率：  配送体积  =  采购体积*（配送换算率/采购换算率）
				var div = accDiv(unitRate,goodsInfo['cgUnit'].rate)
				var divm_v = accMul(goodsVolume,div).toFixed(4)
				$("#goodsVolume").val(divm_v);
				var divm_w = accMul(goodsWeight,div).toFixed(3)
				$("#goodsWeight").val(divm_w);
			}
			//换算单价
			$("#goodsPrice").val(accMul(unitRate,goodsChargingPs).toFixed(3));
			let psNum = $("#sumNum").val();//应入数量
			let goodsPrice = $("#goodsPrice").val();//单价
			//重新计算
			$("#putMoney").val(accMul(psNum,goodsPrice).toFixed(3));//改变金额
			$("#putVolume").val(accMul(psNum,goodsVolume).toFixed(4));//改变应入体积
			$("#putWeight").val(accMul(psNum,goodsWeight).toFixed(3));//改变应入重量


		}
	});
    
    //除以的精确结果
    function accDiv(arg1,arg2){  
	　　var t1=0,t2=0,r1,r2;  
	　　try{
	　　　　t1=arg1.toString().split(".")[1].length;
	　　}catch(e){}

	　　try{
	   　　t2=arg2.toString().split(".")[1].length;
	　　}catch(e){}

	　　with(Math){
	　　　　r1=Number(arg1.toString().replace(".","")); 
	   　　r2=Number(arg2.toString().replace(".","")); 
	　　　　return (r1/r2)*pow(10,t2-t1);  
	　　}
    };
    
    //乘以的精确结果
    function accMul(arg1,arg2){  
    	var m=0,s1=arg1.toString(),
    	s2=arg2.toString();  
    	try{
    	m+=s1.split(".")[1].length}catch(e){}  
    	try{
    	m+=s2.split(".")[1].length}catch(e){}  
    	return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m
    )};
    
    //输入数量
    $("#num").keyup(function(){
    	var goodsName = $("#goodsName").val();
    	if (goodsName==null||goodsName=='') {
    		layer.msg('请选择商品'); 
		} else {
			var num = $("#num").val();//应入数量
			var zpNum = $("#zpNum").val();//应入赠品
			var goodsVolume = $("#goodsVolume").val();//体积
			var goodsWeight = $("#goodsWeight").val();//重量
			var goodsPrice = $("#goodsPrice").val();//单价
			var sumNum = 0
			if(zpNum == '' || typeof parseFloat(zpNum) != 'number'){
				var sumNum = parseFloat(psNum)
			} else {
				var sumNum = parseFloat(num)+parseFloat(zpNum)
			}
			$("#sumNum").val(sumNum);//改变应入总数量
			$("#putMoney").val(accMul(sumNum,goodsPrice).toFixed(3));//改变金额
			$("#putVolume").val(accMul(sumNum,goodsVolume).toFixed(4));//改变应入体积
			$("#putWeight").val(accMul(sumNum,goodsWeight).toFixed(3));//改变应入重量
		}
    });
    
    //输入赠品数量
    $("#zpNum").keyup(function(){
    	var goodsName = $("#goodsName").val();
    	if (goodsName==null||goodsName=='') {
    		layer.msg('请选择商品'); 
		} else {
			var num = $("#num").val();//应入数量
			var zpNum = $("#zpNum").val();//应入赠品
			var goodsVolume = $("#goodsVolume").val();//体积
			var goodsWeight = $("#goodsWeight").val();//重量
			var goodsPrice = $("#goodsPrice").val();//单价
			var sumNum = parseFloat(num)+parseFloat(zpNum)
			$("#sumNum").val(sumNum);//改变应入总数量
			$("#putMoney").val(accMul(sumNum,goodsPrice).toFixed(3));//改变金额
			$("#putVolume").val(accMul(sumNum,goodsVolume).toFixed(4));//改变应入体积
			$("#putWeight").val(accMul(sumNum,goodsWeight).toFixed(3));//改变应入重量
		}
    });
    
    //输入单价
    $("#goodsPrice").keyup(function(){
    	var goodsName = $("#goodsName").val();
    	if (goodsName==null||goodsName=='') {
    		layer.msg('请选择商品'); 
		} else {
			var sumNum = $("#sumNum").val();//应入总数量
			var goodsPrice = $("#goodsPrice").val();//单价
			$("#putMoney").val(accMul(sumNum,goodsPrice).toFixed(3));//改变金额
		}
    });
    
    //输入金额
    $("#putMoney").keyup(function(){
    	var goodsName = $("#goodsName").val();
    	if (goodsName==null||goodsName=='') {
    		layer.msg('请选择商品'); 
		} else {
			var sumNum = $("#sumNum").val();//应入总数量
			var putMoney = $("#putMoney").val();//金额
			$("#goodsPrice").val(accDiv(putMoney,sumNum).toFixed(3));//改变单价
		}
    });

    //返回按钮
    $("#backupPage").click(function () {
    	var Index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(Index);
    });

});